package com.xm.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.xm.common.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;

@Controller
public class AlipayController {
    @RequestMapping("/alipay")
    public void alipay(String billId, BigDecimal money, String account, HttpServletResponse response) throws AlipayApiException {
        String URL = "https://openapi.alipaydev.com/gateway.do"; // alipay测试支付地址
        String APP_ID = "2021000121695304";   // 创建的应用ID
        String APP_PRIVATE_KEY = AlipayConstants.PRIVATE_KEY; //自己的私钥
        String ALIPAY_PUBLIC_KEY = AlipayConstants.ALIPAY_PUBLIC_KEY; //支付宝的公钥
        //下载对应SDK，jar依赖
        AlipayClient alipayClient = new DefaultAlipayClient(URL, APP_ID, APP_PRIVATE_KEY,"json", "UTF-8", ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
//            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest(); //  创建API对应的request
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();    // 创建API对应的request
        alipayRequest.setReturnUrl("http://localhost:8080/index.html");        // 用户确认支付后，支付宝get请求returnUrl
        alipayRequest.setNotifyUrl("http://localhost:8080/payReturnServlet.do");    // 交易成功后，支付宝post请求notifyUrl（商户入参传入）
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", billId);
        bizContent.put("total_amount", money);
        bizContent.put("subject", account);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(bizContent.toString());
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
